package com.suray.socket.system;

import com.suray.socket.ISocketCreate;
import com.suray.socket.SocketInterface;
import com.suray.socket.core.NetAddress;
import com.suray.socket.type.SocketType;

import java.util.Map;
import java.util.Set;

public class SocketCreateImpl implements ISocketCreate {

    @Override
    public SocketInterface addSocket(int socketId, String ip, int port, SocketType socketType) {
        NetAddress netAddress = new NetAddress(socketId, ip, port);
        SocketImpl socket = new SocketImpl(netAddress, socketType);
        socket.start();
        return socket;
    }

    @Override
    public void checkNetAddress(Set<SocketInterface> sockets, NetAddress netAddress) {
        sockets.forEach(socket -> {
            if (((SocketImpl) socket).netAddress.getId().equals(netAddress.getId())
                    || ((SocketImpl) socket).netAddress.equals(netAddress)) {
                throw new RuntimeException("该地址Id已存在，不能使用:" + netAddress);
            }
        });
    }

    @Override
    public SocketInterface findSocket(NetAddress netAddress) {
        return null;
    }

    @Override
    public void deleteSocket(Map<NetAddress, SocketInterface> sockets, SocketInterface socket) {
        socket.close();
        if (sockets.containsValue(socket)) {
            SocketImpl socketImpl = (SocketImpl) socket;
            sockets.remove(socketImpl.netAddress);
        }
    }
}
